package info.hexin.redis.springdata;

import com.esotericsoftware.kryo.Kryo;
import com.esotericsoftware.kryo.io.Input;
import com.esotericsoftware.kryo.io.Output;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.SerializationException;

/**
 * Created by infi.he on 2015/5/18.
 */
public class KryoRedisSerializer<T> implements RedisSerializer<T> {

    @Override
    public synchronized byte[] serialize(Object t) throws SerializationException {
        Kryo kryo = new Kryo();
        kryo.setReferences(false);
        kryo.setRegistrationRequired(false);
        Output output = new Output(4096, -1);
        kryo.writeClassAndObject(output, t);
        return output.toBytes();
    }

    @Override
    public synchronized T deserialize(byte[] bytes) throws SerializationException {
        if (bytes == null) {
            return null;
        }
        Kryo kryo = new Kryo();
        kryo.setReferences(false);
        kryo.setRegistrationRequired(false);
        Input input = new Input(bytes);
        @SuppressWarnings("unchecked")
        T t = (T) kryo.readClassAndObject(input);
        return t;
    }
}
